package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.BusinessStatement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IAppointmentService;
import cn.wolfcode.car.business.service.IBusinessStatementService;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.subject.SubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private IBusinessStatementService businessStatementService;
    @Autowired
    private IAppointmentService appointmentService;

    //分页+过滤
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        List<StatementItem> statementItems=statementItemMapper.selectForList(qo);
        return new TablePageInfo<>(statementItems);
    }

    @Override
    public StatementItem get(Long id) {
        return statementItemMapper.selectByPrimaryKey(id);
    }

    //结算单添加
    public void save(StatementItem statementItem) {
        statementItemMapper.insert(statementItem);
    }

    @Override
    public void update(StatementItem statementItem) {
        statementItemMapper.updateByPrimaryKey(statementItem);
    }

    @Override
    public void deleteBatch(String ids) {

    }


    @Override
    public List<StatementItem> list() {
        return statementItemMapper.selectAll();
    }

    /**
     * 注意：因为有修改服务没选的，这样就还需要修改结算单（没结算），不然后面添加服务数据有错误。
     * @param statementItems
     */
    //保存结算单+结算单明细
    public void saveStatement(List<StatementItem> statementItems) {

        //注意：在传过来的结算单明细，什么都没选的这种情况
        //都需要先删除之前该结算单中的结算单明细

        //1、传过来的结算明细中(总会传)最后一个有：优惠价格，且不需要进行保存需要去除
        StatementItem last=statementItems.remove(statementItems.size()-1);
        statementItemMapper.deleteByStatementId(last.getStatementId());//删除结算单明细
        //2、在保存结算单明细时，需要计算该结算单的消费总计、总服务数量
        BigDecimal totalAmount=new BigDecimal("0.0");
        BigDecimal totalQuantity=new BigDecimal("0");
        System.out.println(statementItems.size());
        if(statementItems.size()>1){
            for (int i = 0; i < statementItems.size(); i++) {
                StatementItem statementItem = statementItems.get(i);
                //结算单明细*数量之后，累加赋值回去
                totalAmount=totalAmount.add(statementItem.getItemPrice().multiply(new BigDecimal(statementItem.getItemQuantity())));
                //计算服务数量,必须赋值回去
                totalQuantity=totalQuantity.add(new BigDecimal(statementItem.getItemQuantity()));

                //因为传过来的结算单明细已经在前端否则好了，故可直接保存
                statementItemMapper.insert(statementItem);
            }
            //3、最后：修改该结算单：消费总计、总服务数量、优惠价格；支付时间、收款人（这些都属性信息需要在结算中添加）
            Long statementId = last.getStatementId();
            BigDecimal discountPrice = last.getItemPrice();//折扣价在 最后结算单明细中
            Date paytime = new Date();
            Long payeeId = ShiroUtils.getUser().getId();//收款人id(一般登录本系统的客服)
            businessStatementService.updateStatement(statementId,totalAmount,
                    totalQuantity,discountPrice,paytime,payeeId);
        }else {
            //如果没有消费任何服务，则除了删除结算单明细外，还需要修改结算单
            businessStatementService.updateStatement(last.getStatementId(),new BigDecimal("0.0"),
                    new BigDecimal("0"),new BigDecimal("0.0"),null,null);
        }


    }
    /**
     * 确认支付：修改结算单的状态+如果是预约单来的则还需要修改预约单的状态
     */
    public void updatePayStatus(Long statementId) {
        BusinessStatement businessStatement = businessStatementService.get(statementId);
        //修改结算单的状态
        businessStatementService.updateStatus(businessStatement.getId(),BusinessStatement.STATUS_PAID);
        //如果是预约单来的则还需要修改预约单的状态
        if(businessStatement.getAppointmentId()!=null){
            Appointment appointment = appointmentService.get(businessStatement.getAppointmentId());
            //预约单状态修改为已结算
            appointmentService.updateAppointStatus(appointment.getId(),Appointment.STATUS_SETTLE);
        }
    }

}
